<template>
  <a-modal :open="open" width="1340px" title="补记账" centered @cancel="onCancel">
    <div>
      <BaseTable
        class="mt-2"
        :loading="loading"
        row-key="id"
        column-code="000107"
        :data-source="dataSource"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
        extra-height="64"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'advTypeCode'">
            <EditCell>
              <a-select
                v-model:value="record.advTypeCode"
                :virtual="false"
                :options="options"
                placeholder="请选择"
                @change="(data) => onChangeClassify(data, record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'advName'">
            <EditCell>
              <SelectTable
                v-model:value="record.advName"
                type="补记账"
                :table-width="800"
                :search-params="{}"
                @select="(data) => onSelectTable(data, record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'count'">
            <EditCell>
              <BaseInput v-model:value="record.count" v-input:int class="text-right" placeholder="请输入" @blur="editRow(record)" />
            </EditCell>
          </template>
          <div v-if="column.dataIndex === 'memo'">
            <EditCell>
              <BaseInput v-model:value="record.memo" placeholder="请输入" @blur="editRow(record)" />
            </EditCell>
          </div>
          <template v-if="column.dataIndex === 'action'">
            <BaseButton confirm-text="确认删除？" type="text" danger size="small" @click="onDelete(record)">删除</BaseButton>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" @click="addRow()"> 新增一条 </a-button>
            <a-button type="primary" @click="saveNewRows()"> 保存入账 </a-button>
          </div>
        </template>
      </BaseTable>
    </div>
    <template #footer>
      <!-- <a-button key="submit" type="primary" :disabled="saveBtnDisabled" :loading="saveLoading" @click="onOk">记账</a-button> -->
      <a-button key="submit" type="primary" @click="onCancel">关闭</a-button>
    </template>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  selectedItem: {
    type: Object,
    default: () => ({})
  }
})

const loading = ref(false)
const dataSource = ref([])
const options = ref([])
const defaultAdvTypeCode = ref('')
// const saveLoading = ref(false)
const saveBtnDisabled = ref(true)

//分类
const onChangeClassify = (data, record) => {
  options.value.forEach((item) => {
    if (item.value === data) {
      record.advTypeName = item.label
    }
  })
  record.advName = ''
  record.advCode = ''
  record.price = ''
  record.unit = ''
}
const onSelectTable = (medicine, row) => {
  row.advName = medicine.mc
  row.advCode = medicine.bh
  row.price = medicine.dj
  row.unit = medicine.dw
  !row.isNew && fetchSave(row)
}
//获取数据
const getData = async () => {
  loading.value = true
  const res = await post('/inp/inpComprehensive/getInpExpensesList', {
    inplsh: props.selectedItem.inplsh,
    lastDeptCode: props.selectedItem.lastDeptCode,
    // status: 2,
    accountType: 1
  })
  loading.value = false
  if (res.code !== 0) return
  dataSource.value = res.data
  if (dataSource.value && dataSource.value.length > 0) {
    saveBtnDisabled.value = false
  } else {
    saveBtnDisabled.value = true
  }
}
//添加行
const addRow = () => {
  const key = `row-${dataSource.value.length}`
  const addRow = {
    key,
    isNew: true,
    advTypeName: '膳食费',
    advTypeCode: defaultAdvTypeCode.value,
    inplsh: props.selectedItem.inplsh,
    deptCode: props.selectedItem.lastDeptCode,
    accountType: 1
  }
  dataSource.value.push(addRow)
}
const saveNewRows = () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item) => {
    if (item.count) {
      fetchSave(item)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}

//修改行
const editRow = (row) => !row.isNew && fetchSave(row)
// 保存行
const fetchSave = async (row) => {
  const { code, msg } = await post('/inp/inpComprehensive/doSaveInpExpenses', row)
  if (code !== 0) return message.error(msg || '操作失败')
  getData()
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
}
//删除行
const onDelete = async (row) => {
  if (!row.isNew) {
    const { code, msg } = await post('/inp/inpComprehensive/doDelInpExpenses', {
      id: row?.id
    })
    if (code !== 0) return message.error(msg || '删除失败')
    message.success(msg)
    getData()
  } else {
    dataSource.value = dataSource.value.filter((item) => {
      return item.key !== row.key
    })
    message.success('删除成功')
  }
}
const getProjectList = async () => {
  const { code, data } = await post('/drugStorage/comprehenive/getMedicalProjectList')
  if (code !== 0) return
  options.value = data.map((item) => {
    if (item.mc === '膳食费') {
      defaultAdvTypeCode.value = item.bh.toString()
    }
    return {
      label: item.mc,
      value: item.bh.toString()
    }
  })
}
// const onOk = async () => {
//   const ids = dataSource.value.map((item) => item.id)
//   if (ids.length <= 0) return message.error('暂无要记账的数据')
//   const { code, msg } = await post('/inp/inpComprehensive/doCancelExpenses', {
//     ids: ids,
//     inplsh: props.selectedItem.inplsh,
//     status: 2
//   })
//   if (code !== 0) return message.error(msg || '操作失败')
//   message.success(msg || '操作成功')
//   emit('success')
//   onCancel()
// }
// const getAdvTypeName = (code) => {
//   const obj = options.value.find((item) => item.value === code)
//   if (obj.label) return obj.label
// }
watch(
  () => props.open,
  (val) => {
    if (val && props.selectedItem?.brId) {
      getProjectList()
      getData()
      // formState.value = { ...props.rowData }
    }
  },
  {
    immediate: true
  }
)

const onCancel = () => {
  emit('success')
  emit('update:open', false)
}
</script>
<style lang="less">
.bg-black-1 {
  background: rgba(0, 0, 0, 0.1);
}
</style>
